package com.baseweb.webadmin.controller.app;

import com.baseweb.webadmin.alipay.util.httpClient.HttpResponse;
import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.ByUserTrolleyBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.DateUtil;
import com.baseweb.webadmin.core.util.StringUtil;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import com.google.common.base.Strings;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhouxin on 2017/8/22.
 */
@Controller
@RequestMapping(value = "/appApiTrolley")
public class TrolleyAppController  extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserOrderService userOrderService;


    //购物车
    @ResponseBody
    @RequestMapping(value = "/getTrolleylist")
    public Map<String, Object> getTrolleylist(@RequestParam(value = "userId", required = true) Integer userId) {

        List<ByUserTrolleyBvo> byUserTrolleys = userService.selectByUserTrolleyList(userId);

        return success(byUserTrolleys,"购物车查询成功");
    }
    /**
     * 加入购物车
     * @param byUserTrolley
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addTrolley", method = RequestMethod.POST)
    public Map<String, Object> addTrolley(ByUserTrolley byUserTrolley, @RequestParam(value = "schedule_date",required = false) String schedule_date){
        byUserTrolley.setCreateTime(new DateTime());
        byUserTrolley.setUpdateTime(new DateTime());
        byUserTrolley.setScheduleDate(DateUtil.getDateTime(schedule_date));
        int result = userService.insertTrolley(byUserTrolley);

        if(result > 0){
            return success(byUserTrolley,"加入购物车成功");
        }else{
            return fail("加入购物车失败");
        }
    }

    @RequestMapping(value = "/deleteTrolley")
    @ResponseBody
    public Map<String, Object> deleteTrolley(@RequestParam(value = "trolleyId",required = false) Integer trolley_id) {

        try{
            userService.deleteTrolley(trolley_id);
            return success(trolley_id,"删除购物车成功");
        }catch (Exception e){
            return fail("删除购物车失败");
        }

    }

    @RequestMapping(value = "/submitOrder")
    @ResponseBody
    public Map<String, Object> submitOrder(@RequestParam(value = "ids", required = true) String ids,
                              @RequestParam(value = "payStatus",defaultValue = "1") Integer payStatus,
                              @RequestParam(value = "payFor",defaultValue = "1") String payFor,
                              @RequestParam(value = "userId", required = true) Integer userId) {
        String orderIds = "";
        try{
            Map<Integer, List<ByUserTrolley>> tmpMap = new HashMap<Integer, List<ByUserTrolley>>();
            String[] idArr = ids.split(",");
            if(idArr != null && idArr.length > 0){
                for(String id : idArr){
                    ByUserTrolley current = userService.findTrolley(Integer.valueOf(id));
                    if(tmpMap.containsKey(current.getBizUserId())){
                        tmpMap.get(current.getBizUserId()).add(current);
                    }else{
                        List<ByUserTrolley> tmpList = new ArrayList<ByUserTrolley>();
                        tmpList.add(current);
                        tmpMap.put(current.getBizUserId(), tmpList);
                    }
                    userService.deleteTrolley(Integer.valueOf(id));
                }
            }
            for(Iterator it = tmpMap.keySet().iterator(); it.hasNext();) {
                Integer mKey = (Integer) it.next();

                ByUserOrder order = new ByUserOrder();
                order.setUserId(userId);

                if(StringUtil.isNotBlank(payFor) && "bank".equals(payFor)){
                    order.setPayType(PayType.BANK_PAY.getCode());
                }else{
                    order.setPayType(PayType.ALIPAY.getCode());
                }
                order.setPayStatus(OrderPayStatus.NOT_PAY.getCode());
//                order.setPayStatus(pay_status);
                order.setBizUserId(mKey);
                order.setPrice(BigDecimal.ZERO);
                order.setDeposit(BigDecimal.ZERO);
                order.setNeedPayPrice(BigDecimal.ZERO);
                order.setCreateTime(new DateTime());
                order.setUpdateTime(new DateTime());

                userOrderService.insertByUserOrder(order);
                BigDecimal orderPrice = BigDecimal.ZERO;
                BigDecimal deposit = BigDecimal.ZERO;
                for (ByUserTrolley current : tmpMap.get(mKey)){
                    ByUserBizProduct byUserBizProduct = userService.findBizProduct(current.getProductId());

                    ByUserOrderDetail detail = new ByUserOrderDetail();
                    detail.setOrderId(order.getId());

                    if(current.getAmount() == null || current.getAmount() < 1){
                        detail.setAmount(1);
                    }else{
                        detail.setAmount(current.getAmount());
                    }

                    detail.setUserId(userId);
                    detail.setProductId(current.getProductId());
                    detail.setPrice(byUserBizProduct.getCurrentPrice().multiply(new BigDecimal(current.getAmount())));

                    orderPrice = orderPrice.add(detail.getPrice());

                    detail.setScheduleDate(current.getScheduleDate());
                    detail.setDinnerType(current.getDinnerType());
                    detail.setBizUserId(byUserBizProduct.getUserId());
//                        detail.setOrderId(order.getId());

                    BigDecimal per = byUserBizProduct.getDeposit() == null ? new BigDecimal("0") : byUserBizProduct.getDeposit().divide(new BigDecimal("100"));
                    detail.setDeposit(per.multiply(detail.getPrice()));
                    detail.setCreateTime(new DateTime());
                    detail.setUpdateTime(new DateTime());
                    userOrderService.insertByUserOrderDetail(detail);
                    deposit = deposit.add(detail.getDeposit());
                    //add Schedule
                    ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
                    byUserBizSchedule.setUserId(current.getBizUserId());
                    byUserBizSchedule.setOrderBy(detail.getUserId());
                    byUserBizSchedule.setScheduleDate(detail.getScheduleDate());
                    byUserBizSchedule.setStatus(BaseState.NORMAL.getCode());
                    byUserBizSchedule.setScheduleType(ScheduleType.getByName(detail.getDinnerType()).getCode());
                    byUserBizSchedule.setCreateTime(new DateTime());
                    byUserBizSchedule.setUpdateTime(new DateTime());

                    userOrderService.insertSchedule(byUserBizSchedule);
                }
                ByUserOrder newOrder = userOrderService.findByUserOrder(order.getId());

                //更新订单价格
                newOrder.setPrice(orderPrice);
//                if (currentBizUser.getBizWorkType().intValue() == 1){ //策划师
//                    newOrder.setStatus(OrderStatus.NEW_ORDER.getCode());
//                }else {
                newOrder.setStatus(OrderStatus.VERIFY_ORDER.getCode());
//                }

//                newOrder.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(newOrder.getPrice()));
                newOrder.setDeposit(deposit);
                newOrder.setNeedPayPrice(newOrder.getPrice().subtract(newOrder.getDeposit()));

                userOrderService.insertByUserOrder(newOrder);
                orderIds += newOrder.getId() + ",";
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("购物车结算失败");
        }
        if(Strings.isNullOrEmpty(orderIds)){
            return fail("购物车结算失败了");
        }else{
            String payParam = userOrderService.ordersPay(orderIds,userId,payStatus,payFor);
            Map<String,String> map = new HashMap<>();
            map.put("payParam",payParam);
            return  success(payParam,"购物车结算成功");
        }
    }
}
